package com.keguoyu.easymvp.business;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableTable;

import java.util.List;

import static com.google.common.collect.ImmutableList.of;

/**
 * 状态变化：
 * CREATE -> BIND -> UNBIND -> DESTROY
 *
 * @author keguoyu
 */
final class BusinessStateController {

  private static final
  ImmutableTable<Business.BusinessState, Business.BusinessState, List<Business.BusinessState>> STATE_TABLE =
      ImmutableTable.<Business.BusinessState, Business.BusinessState, List<Business.BusinessState>>builder()
          .put(Business.BusinessState.INIT, Business.BusinessState.CREATE, of(
              Business.BusinessState.CREATE))
          .put(Business.BusinessState.CREATE, Business.BusinessState.BIND, of(
              Business.BusinessState.BIND))
          .put(Business.BusinessState.BIND, Business.BusinessState.BIND, of(
              Business.BusinessState.UNBIND, Business.BusinessState.BIND))
          .put(Business.BusinessState.BIND, Business.BusinessState.UNBIND, of(
              Business.BusinessState.UNBIND))
          .put(Business.BusinessState.UNBIND, Business.BusinessState.DESTROY, of(
              Business.BusinessState.DESTROY))
          .put(Business.BusinessState.BIND, Business.BusinessState.DESTROY, of(
              Business.BusinessState.UNBIND, Business.BusinessState.DESTROY))
          .put(Business.BusinessState.INIT, Business.BusinessState.DESTROY, of(
              Business.BusinessState.NONE))
          .build();

  static void goToState(Business.BusinessState from, Business.BusinessState to,
                        Business.BusinessState.BusinessStateCallBack callBack) {

    List<Business.BusinessState> states = STATE_TABLE.get(from, to);
    Preconditions.checkState(states != null, "不能从 " + from + " 跳到 " + to);
    for (Business.BusinessState state : states) {
      callBack.onState(state);
    }
  }

}
